package com.yupi.shortchain.utils;

import cn.hutool.core.text.CharSequenceUtil;
import com.yupi.shortchain.model.entity.UrlRelate;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

@Slf4j
public class JsoupUtil {
    public static void setUrlTitleAnd(String url, UrlRelate urlRelate) {
        //通过url解析网址title和logo
        String title;
        try {
            //还是一样先从一个URL加载一个Document对象。
            Document doc = Jsoup.connect(url).get();
            Elements links = doc.select("head");
            Elements titleLinks = links.get(0).select("title");
            title = titleLinks.get(0).text();
            log.info("成功解析网站标题============={}", title);
            if (CharSequenceUtil.isBlank(urlRelate.getTitle())) {
                urlRelate.setTitle(title);
            }
            Element faviconLink = doc.head().select("link[href~=.*\\.(ico|png)]").first();
            String faviconUrl = faviconLink != null ? faviconLink.attr("href") : "";

            // Sometimes the favicon URL is relative, so we might need to make it absolute
            if (!(faviconUrl.toLowerCase().startsWith("https") || faviconUrl.toLowerCase().startsWith("http"))) {
                faviconUrl = url + faviconUrl;
            }
            log.info("网站icon============={}", faviconUrl);
            if (CharSequenceUtil.isBlank(urlRelate.getLongUrl())) {
                urlRelate.setLongUrl(faviconUrl);
            }

        } catch (Exception e) {
            log.error("通过url={} 网址解析title和logo 异常：{}", url, e.getMessage());
            e.printStackTrace();
        }
    }

}
